<!-- 定义表单 表单中有表单项 表单需要绑定对象， 表单项需要绑定对象的成员变量 提交表单需要使用ajax方法提交json对象 -->
<!-- el-cascader 级联下拉选择框 需要通过options指定选项，这里绑定了options变量所以需要自己在data定义options 变量 绑定了change事件（当用户选择性的选项时候激活 handleChange，将多级选择的地址值组合 赋值给指定对象的属性）并且选中的值绑定给
selectedOptions
-->
<template>
    <div>
      <el-dialog title="新增用戶" :visible.sync="addDialogIsShow" :before-close="handleClose" :close-on-click-modal="false">
        <el-form   label-width="120px"  ref="addStudentUploadForm">
          <!-- 代码中的1表示第几个 和引入js的type变量对应 -->
          <!-- action 就是原来普通form action也就是提交地址 所以对应方法返回后端正确的action请求地址-->
          <el-form-item label="头像">
            <el-upload
              class="upload"
              :action="getUploadUrl"
              list-type="picture-card"
              :limit="1"
              accept="image/*"
              :on-change="(file,fileList)=>{imgHandleChange(file,fileList,1,this,'addStudentUploadForm','head')}"
              :on-remove="(file,fileList)=>{imgHandleRemove(1,this)}"
              :on-before="(file,fileList)=>{imghandleBeforeUpload(file,1,this)}"
              :auto-upload="false"
              :file-list="fileList[0]"
              ref="file1">
              <i class="el-icon-plus"></i>
            </el-upload>
            <!--<viewer-dialog ref="viewer" :images="imagesUp"></viewer-dialog>-->
          </el-form-item>
        </el-form>
      <el-form :model="student" :rules="addStudentRules" ref="addStudentForm">

        <el-form-item  label="学号：" label-width="100px" prop="sno">
          <el-col :span="16">
           <el-input v-model="student.sno" placeholder="请填入学号"/>
          </el-col>
        </el-form-item>

        <el-form-item  label="姓名：" label-width="100px" prop="name">
          <el-col :span="16">
           <el-input v-model="student.name" placeholder="请填入姓名"/>
         </el-col>
        </el-form-item>

        <el-form-item  label="性别：" label-width="100px">
          <el-col :span="8">
              <el-radio v-model="student.sex" label="男">男</el-radio>
              <el-radio v-model="student.sex" label="女">女</el-radio>
          </el-col>
        </el-form-item>

        <el-form-item  label="身高：" label-width="100px">
          <el-col :span="16">
            <el-input v-model="student.high" placeholder="请填入身高"/>
          </el-col>
        </el-form-item>
        <el-form-item  label="出生日期：" label-width="100px">
          <el-col :span="8">
            <el-date-picker
              v-model="student.birthday"
              type="date"
              placeholder="选择日期">
            </el-date-picker>
          </el-col>
        </el-form-item>
        <el-form-item  label="入学日期：" label-width="100px">
          <el-col :span="8">
            <el-date-picker
              v-model="student.jointime"
              type="date"
              placeholder="选择日期">
            </el-date-picker>
          </el-col>
        </el-form-item>
        <el-form-item  label="联系电话：" label-width="100px" prop="homephone">
          <el-col :span="16">
            <el-input  v-model="student.homephone" placeholder="请填入联系电话" @input="updateView($event)"/>
          </el-col>
        </el-form-item>

        <el-form-item  label="床位号：" label-width="100px">
          <el-col :span="16">
            <el-input v-model="student.bedno" placeholder="请填入床位号"/>
          </el-col>
        </el-form-item>
        <el-form-item  label="家庭住址：" label-width="100px">
          <el-col :span="16">
            <el-input v-model="student.address" placeholder="请填入家庭住址"/>
          </el-col>
        </el-form-item>
        <el-form-item  label="入学分数：" label-width="100px">
          <el-col :span="16">
            <el-input v-model="student.avgscore" placeholder="请填入入学分数"/>
          </el-col>
        </el-form-item>
        <el-form-item label="籍贯">
          <el-cascader
            size="large"
            :options="options"
            v-model="selectedOptions"
            @change="handleChange"
          >
          </el-cascader>


        </el-form-item>
        <el-form-item  label="班级：" label-width="100px">
          <el-col :span="16">
            <el-select v-model="student.cno" placeholder="请选择">
              <el-option
                v-for="clazz in clazzes"
                :key="clazz.cno"
                :label="clazz.cname"
                :value="clazz.cno">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>



        <el-row>
          <el-col :span="16">
            <span class="addSpan">&nbsp;</span>
          </el-col>
          <el-col :span="8">
        <el-button type="primary" @click="addStudent">添加课程</el-button>
            </el-col>
        </el-row>
      </el-form>
      </el-dialog>
    </div>
</template>

<script>
  import api from "../../../../axios/api.js"
  import rules from "../../../../static/js/validator/rules.js"
  import { regionData, CodeToText } from "element-china-area-data";
  import utils from "../../../../static/js/utils/upload.js"
    export default {
        props:["addDialogIsShow", "clazzes"],
        name: "add",
        data(){
          return {
            student:{},
            //行政区使用
            options: regionData,
            selectedOptions: []

            //行政区使用结束
            ,
            //校验
            addStudentRules: {
              sno: [
                {required: true, message: "学号不能为空", trigger: 'blur'},
                {validator: this.validateLength, trigger: 'blur'}
              ],
              name: [{required: true, message: "姓名不能为空", trigger: 'blur'}, {
                pattern: /^[\u0391-\uFFE5A-Za-z]+$/,
                message: '姓名必须为中文',
                trigger: 'blur'
              }],
              homephone: [{required: true, message: "电话不能为空", trigger: 'blur'}, {
                validator:rules.FormValidate.Form().validatePhone,trigger:'change'
              }]
            },
            //校验结束
            //上传使用
            fileList: [[],[],[]], //缓存区文件
            uploadFile:[[],[],[]], //  上传用文件
            formData:{files:[]},
            imagesUp:null,
            //上传使用结束
          }
        },
      methods:{
        addStudent:function () {
          this.$refs['addStudentForm'].validate(valid => {//此处refs对象和标签上的ref对应
            if (valid) {

              api.setDataFromAxios("/api/TestWeb/studentController/addStudent", this.student, "post", null).then(
                dto => {
                  this.$message.success("课程添加成功");
                  handleClose();
                }
              )
            } else {
              this.$message.warning("请正确格式填写后提交");
              return
            }
          })
        },
        //查询全部班级提供给下拉列表选择
        getAllClazzs:function(){
          api.setDataFromAxios("/api/TestWeb/clazzController/getClazzs",null,"get",null).then(
            dto=>{
              this.clazzes = dto.tList;
            }
          )
        },
        //行政区使用
        handleChange() {
          var loc = "";
          var regCode = "";
          for (let i = 0; i < this.selectedOptions.length; i++) {
            loc += CodeToText[this.selectedOptions[i]];
            regCode =this.selectedOptions[i]
          }
          console.log(loc);
          console.log(regCode);
          this.student.area = loc+","+regCode;
        },
        //行政区使用结束
         //提供给change事件刷新输入
        updateView(e) {
          this.$forceUpdate();
        },
        handleClose:function(){
          //给父组件传参
          this.$emit("closeAddDialog");
        },
        //多文件上传
        imghandleBeforeUpload(file,type,vm) {
          return utils.UPLOAD.Upload().handleBeforeUpload(file,type,vm);
        },
        imgHandleChange(file, fileList, type,vm,modelName,name) {
          if(vm.fileList[type].length!=0){
            alert("请先删除再提交")
          }
          return utils.UPLOAD.Upload().handleChange(file, fileList, type,vm,modelName,name);
        },
        imgHandleRemove(type,vm) {

          return utils.UPLOAD.Upload().handleRemove( type,vm);
        },
        uploadImg:function(modelName,name){
          //  使用formdata格式
          let formData = new FormData();//准备一个空的表单对象
          formData.append("model",modelName);//图片上传子目录名放入表单对象
          console.log(formData);
          console.log(this.formData.files[name]);
          if (this.formData.files[name]) {
            formData.append("file", this.formData.files[name]);//文件放入表单对象
          }
          console.log("----------------------------");
          console.log(formData);
          //为什么要封装一下方法 1.每个vue组件有自己的一些参数处理，简化调用本来这个setDataFromAxios这个方法属于api 重新封装就属于当前页面
          api.setDataFromAxios("/api/TestWeb/uploadController/upload",formData,"post",{headers: { "Content-Type": "multipart/form-data" }})
            .then(dto=>{
              if(dto.code==200){
                this.$message.success (dto.msg);
                console.log(this);
                this.student.imgsrc = dto.tList[0];
                console.log( dto.tList[0]);
                console.log(this.student);
              }else{
                this.$message.error (dto.msg);
              }
            });//.then方法 就是当服务器有返回的时候执行回调函数，对比jquery的ajax success:function（data）
        },
        //多文件上传结束
      },
      created() {

      },
      computed:{
        getUploadUrl(){
          return      "/api/TestWeb/uploadController/upload";
        }
      },
    }
</script>

<style scoped>
</style>
